package org.kiwi.data.lb;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.util.Assert;

import java.util.*;

/**
 * Created by jack on 16/10/26.
 */
public class RandomLoadBalanceStrategy extends AbstractLoadBalanceStrategy<String> {

    private List<String> failedTargets;
    private final Random random = new Random();

    public RandomLoadBalanceStrategy(List<String> targets, String writeDsName) {
        Assert.notEmpty(targets, "targets must not be empty");
        Assert.hasText(writeDsName, "writeDsName is required");

        this.writeDsName = writeDsName;
        this.targets = Collections.synchronizedList(targets);
        this.failedTargets = Collections.synchronizedList(new ArrayList<String>(targets.size()));
    }

    @Override
    public synchronized String elect() {
        if (CollectionUtils.isEmpty(this.targets)) {
            return null;
        }
        return this.targets.get(this.random.nextInt(this.targets.size()));
    }

    @Override
    public synchronized void removeTarget(String target) {
        if (this.targets.contains(target)) {
            this.targets.remove(target);
            this.failedTargets.add(target);
        }
    }

    @Override
    public synchronized void recoverTarget(String target) {
        if (this.failedTargets.contains(target)) {
            this.targets.add(target);
            this.failedTargets.remove(target);
        }
    }

    @Override
    public Set<String> getFailedTargets() {
        return new HashSet<>(this.failedTargets);
    }
}

